<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备IP" prop="deviceIp">
        <el-input
            v-model="queryParams.deviceIp"
            placeholder="请输入设备IP"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="deviceList.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
        style="width: 100%;"
    >
      <el-table-column label="序号" width="50" type="index" align="center">
        <template #default="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备编号" align="center" prop="deviceId" :show-overflow-tooltip="true" />
      <el-table-column label="设备名称" align="center" prop="deviceName" :show-overflow-tooltip="true" />
      <el-table-column label="设备IP" align="center" prop="deviceIp" :show-overflow-tooltip="true" />
      <el-table-column label="温度 (°C)" align="center" prop="temperature" :show-overflow-tooltip="true" />
      <el-table-column label="湿度 (%)" align="center" prop="humidity" :show-overflow-tooltip="true" />
      <el-table-column label="光照 (Lux)" align="center" prop="light" :show-overflow-tooltip="true" />
      <el-table-column label="氮 (mg/L)" align="center" prop="nitrogen" :show-overflow-tooltip="true" />
      <el-table-column label="磷 (mg/L)" align="center" prop="phosphorus" :show-overflow-tooltip="true" />
      <el-table-column label="钾 (mg/L)" align="center" prop="potassium" :show-overflow-tooltip="true" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="showTrendDialog(scope.row)">趋势</el-button>
<!--          <el-button link type="primary" icon="View" @click="goToDeviceDetail(scope.row)">详情</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="pageNum" v-model:limit="pageSize" @pagination="getList" />

    <!-- 趋势图表对话框 -->
    <el-dialog
        title="设备数据趋势"
        v-model="trendDialogVisible"
        width="50%"
        :before-close="handleCloseTrendDialog"
    >
      <div class="chart-container">
        <el-tabs v-model="activeChart">
          <el-tab-pane label="温度" name="temperature">
            <LineChart :chart-data="temperatureChartData" :options="chartOptions" />
          </el-tab-pane>
          <el-tab-pane label="湿度" name="humidity">
            <LineChart :chart-data="humidityChartData" :options="chartOptions" />
          </el-tab-pane>
          <el-tab-pane label="光照" name="light">
            <LineChart :chart-data="lightChartData" :options="chartOptions" />
          </el-tab-pane>
          <el-tab-pane label="氮" name="nitrogen">
            <LineChart :chart-data="nitrogenChartData" :options="chartOptions" />
          </el-tab-pane>
          <el-tab-pane label="磷" name="phosphorus">
            <LineChart :chart-data="phosphorusChartData" :options="chartOptions" />
          </el-tab-pane>
          <el-tab-pane label="钾" name="potassium">
            <LineChart :chart-data="potassiumChartData" :options="chartOptions" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <template #footer>
        <el-button @click="trendDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue';
import { LineChart } from 'vue-chart-3';
import { Chart, registerables } from 'chart.js';
const router = useRouter();
// 注册 Chart.js 组件
Chart.register(...registerables);

const { proxy } = getCurrentInstance();

// 数据状态
const deviceList = ref([]);
const loading = ref(true);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const queryParams = ref({
  deviceName: undefined,
  deviceIp: undefined,
});
const trendDialogVisible = ref(false);
const activeChart = ref('temperature');
const selectedDevice = ref(null);

// 模拟数据
const mockData = ref([
  {
    deviceId: 'DEV001',
    deviceName: '传感器1',
    deviceIp: '192.168.1.101',
    temperature: 25.3,
    humidity: 55,
    light: 1500,
    nitrogen: 15.2,
    phosphorus: 10.8,
    potassium: 20.1,
    updateTime: new Date().getTime(),
    history: {
      temperature: [25.3, 25.5, 25.0, 26.1, 24.8, 25.3],
      humidity: [55, 56, 54, 57, 55, 56],
      light: [1500, 1450, 1550, 1480, 1520, 1500],
      Hannah: [15.2, 15.0, 15.5, 14.8, 15.3, 15.2],
      nitrogen: [15.2, 15.0, 15.5, 14.8, 15.3, 15.2],
      phosphorus: [10.8, 10.5, 11.0, 10.7, 10.9, 10.8],
      potassium: [20.1, 20.0, 20.3, 19.8, 20.2, 20.1],
    },
  },
  // 更多模拟设备数据...
]);

// 图表配置
const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    x: { display: true, title: { display: true, text: '时间' } },
    y: { beginAtZero: false, title: { display: true, text: '数值' } },
  },
  plugins: { legend: { display: false } },
};

// 计算图表数据
const temperatureChartData = computed(() => ({
  labels: ['10s ago', '8s ago', '6s ago', '4s ago', '2s ago', 'Now'],
  datasets: [{
    data: selectedDevice.value?.history.temperature || [],
    borderColor: 'rgba(239, 68, 68, 0.8)',
    backgroundColor: 'rgba(239, 68, 68, 0.2)',
    tension: 0.4,
    fill: true,
  }],
}));
const humidityChartData = computed(() => ({
  labels: ['10s ago', '8s ago', '6s ago', '4s ago', '2s ago', 'Now'],
  datasets: [{
    data: selectedDevice.value?.history.humidity || [],
    borderColor: 'rgba(59, 130, 246, 0.8)',
    backgroundColor: 'rgba(59, 130, 246, 0.2)',
    tension: 0.4,
    fill: true,
  }],
}));
const lightChartData = computed(() => ({
  labels: ['10s ago', '8s ago', '6s ago', '4s ago', '2s ago', 'Now'],
  datasets: [{
    data: selectedDevice.value?.history.light || [],
    borderColor: 'rgba(234, 179, 8, 0.8)',
    backgroundColor: 'rgba(234, 179, 8, 0.2)',
    tension: 0.4,
    fill: true,
  }],
}));
const nitrogenChartData = computed(() => ({
  labels: ['10s ago', '8s ago', '6s ago', '4s ago', '2s ago', 'Now'],
  datasets: [{
    data: selectedDevice.value?.history.nitrogen || [],
    borderColor: 'rgba(34, 197, 94, 0.8)',
    backgroundColor: 'rgba(34, 197, 94, 0.2)',
    tension: 0.4,
    fill: true,
  }],
}));
const phosphorusChartData = computed(() => ({
  labels: ['10s ago', '8s ago', '6s ago', '4s ago', '2s ago', 'Now'],
  datasets: [{
    data: selectedDevice.value?.history.phosphorus || [],
    borderColor: 'rgba(34, 197, 94, 0.8)',
    backgroundColor: 'rgba(34, 197, 94, 0.2)',
    tension: 0.4,
    fill: true,
  }],
}));
const potassiumChartData = computed(() => ({
  labels: ['10s ago', '8s ago', '6s ago', '4s ago', '2s ago', 'Now'],
  datasets: [{
    data: selectedDevice.value?.history.potassium || [],
    borderColor: 'rgba(34, 197, 94, 0.8)',
    backgroundColor: 'rgba(34, 197, 94, 0.2)',
    tension: 0.4,
    fill: true,
  }],
}));

// 时间格式化函数
const parseTime = (time) => {
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 查询设备列表
function getList() {
  loading.value = true;
  // 模拟 API 调用
  setTimeout(() => {
    const filteredData = mockData.value.filter(device => {
      return (
          (!queryParams.value.deviceName || device.deviceName.includes(queryParams.value.deviceName)) &&
          (!queryParams.value.deviceIp || device.deviceIp.includes(queryParams.value.deviceIp))
      );
    });
    deviceList.value = filteredData.map(device => ({
      ...device,
      temperature: (20 + Math.random() * 10).toFixed(1),
      humidity: (40 + Math.random() * 20).toFixed(0),
      light: (1000 + Math.random() * 1000).toFixed(0),
      nitrogen: (10 + Math.random() * 10).toFixed(1),
      phosphorus: (5 + Math.random() * 10).toFixed(1),
      potassium: (15 + Math.random() * 10).toFixed(1),
      updateTime: new Date().getTime(),
    }));
    total.value = filteredData.length;
    loading.value = false;
  }, 500);
}
//路由跳转
const goToDeviceDetail = (row) => {
  router.push({ path: '/dataMonitoring/equipDetail', query: { deviceId: row.deviceId } });
};

// 搜索按钮操作
function handleQuery() {
  pageNum.value = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

// 显示趋势图表对话框
function showTrendDialog(row) {
  selectedDevice.value = row;
  trendDialogVisible.value = true;
  activeChart.value = 'temperature';
}

// 关闭趋势对话框
function handleCloseTrendDialog() {
  trendDialogVisible.value = false;
  selectedDevice.value = null;
}

// 初始加载数据
getList();
</script>

<style scoped>
.app-container {
  padding: 20px;

  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.chart-container {
  height: 300px;
  margin-top: 20px;
}
</style>